<template>
    <div class="editor">
        <h2>新增知识库</h2>
        <el-form :model="form" :rules="rules" ref="formRef">
            <el-form-item prop="libraryName">
                <el-input v-model="form.libraryName" placeholder="知识库名称" maxlength="16" show-word-limit />
            </el-form-item>
            <el-form-item prop="libraryDescription">
                <el-input v-model="form.libraryDescription" maxlength="1024" show-word-limit type="textarea"
                    placeholder="知识库描述" />
            </el-form-item>
            <el-switch v-model="form.isPublic" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                active-value="1" inactive-value="0" active-text="公开" inactive-text="私有" />
        </el-form>
        <button @click="submitKnowledge">提交</button>
    </div>

</template>

<script setup>
import { reactive, ref } from 'vue';
import require from '../require';
import { ElMessage } from 'element-plus';

const emit = defineEmits(['add-knowledge']);

const form = reactive({
    libraryName: '我的第一个知识库',
    libraryDescription: '我的第一个知识库',
    isPublic: "1"
})

const formRef = ref(null);

const validateName = (rule, value, callback) => {
    const pattern = /^[\u4e00-\u9fa5a-zA-Z0-9_]{1,16}$/;
    if (!value.match(pattern)) {
        callback(new Error('知识库名称只能包含中文、字母、数字、下划线，且长度为1~16个字符'));
    } else {
        callback();
    }
}

const rules = {
    libraryName: [
        { required: true, message: '请输入知识库名称', trigger: 'blur' },
        { validator: validateName, trigger: 'blur'}
    ],
    libraryDescription: [
        { required: true, message: '请输入知识库描述', trigger: 'blur' },
        { max: 1024, message: '知识库描述长度不能超过1024个字符', trigger: 'blur' }
    ]
};

const res = ref(null);

const submitKnowledge = async () => {
    //ElMessage.success('新增知识库成功')
    const formData = {
        libraryName: form.libraryName,
        libraryDescription: form.libraryDescription,
        isPublic: parseInt(form.isPublic, 10), // 转换为整数
    }
    const res = await require.post('user/addLibrary', formData);
    if (res!== null && typeof res !== 'number') {
        ElMessage.success('新增知识库成功')
        emit('add-knowledge', res.data);
    }
};
</script>

<style scoped>
.editor {
  display: flex;
  flex-direction: column;
  gap: 10px;
  width: 40%;
}

input,
textarea {
  padding: 8px;
}

button {
  padding: 8px;
  background-color: #4caf50;
  color: white;
  border: none;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}
</style>
